package com.hljcert.data.service.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hljcert.data.service.common.config.SystemProperties;
import com.hljcert.data.service.common.result.Result;
import com.hljcert.data.service.common.util.PasswordUtil;
import com.hljcert.data.service.system.entity.SysUser;
import com.hljcert.data.service.system.mapper.SysUserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SystemProperties systemConfig;

    public Result<String> add(SysUser entity) {
        String encryptPwd = PasswordUtil.encrypt(entity.getLoginName(), entity.getPassword(), systemConfig.getAdminSecretKey());
        entity.setPassword(encryptPwd);
        this.sysUserMapper.insert(entity);
        return Result.OK();
    }

    public Result<String> update(SysUser entity){
        if (StringUtils.isNotBlank(entity.getPassword())) {
            String encryptPwd = PasswordUtil.encrypt(entity.getLoginName(), entity.getPassword(), systemConfig.getAdminSecretKey());
            entity.setPassword(encryptPwd);
        } else {
            entity.setPassword(null);
        }
        this.sysUserMapper.updateById(entity);
        return Result.OK();
    }

    public Result<String> delete(String id){
        this.sysUserMapper.deleteById(id);
        return Result.OK();
    }

    public Result<IPage<SysUser>> getPageList(Integer pageNo, Integer pageSize, String loginName, String name){
        IPage<SysUser> page = Page.of(pageNo , pageSize);
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like("name", name);
        }
        if (StringUtils.isNotBlank(loginName)) {
            queryWrapper.like("login_name", loginName);
        }
        IPage<SysUser> result = this.sysUserMapper.selectPage(page, queryWrapper);
        result.getRecords().stream().forEach(e -> { e.setPassword(""); });
        return Result.OK(result);
    }

    public SysUser getAdminByLoginName(String loginName){
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", loginName);
        return this.sysUserMapper.selectOne(queryWrapper);
    }
}